package com.bobo.web.provider.util.commutils;

import com.google.common.collect.Sets;

import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author xuehui7
 * @date 2018/12/5
 * @desc 唯一ID生成器
 */
public class IdGen {
    /**
     * 10个并发 运行十万次 无重复；运行百万次 10～20个重复；完成满足现行业务需求
     *
     * @return
     */
    public static Long next() {
        int code = (int) (Math.random() * (999999999 - 100000000)) + 100000000; // 产生1000-9999之间的一个随机数
        String codeStr = String.valueOf(code) + ThreadLocalRandom.current().nextInt(10);
        return Long.parseLong(codeStr);
    }

    public static void main(String[] args) {
        Set<Long> set = Sets.newConcurrentHashSet();
        System.out.println("end");
        ExecutorService executorService = Executors.newFixedThreadPool(100);
        for (int i = 0; i < 100; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 10000; i++) {
                        Long l = next();
                        if (set.contains(l)) {
                            System.out.println("重复" + l);
                        } else {
                            set.add(l);
                        }
                    }
                }
            });
        }
    }
}

